package com.yt.system.utils;

import com.yt.system.domain.User;

import java.util.*;

/**
 * @author 高铭
 * @date 2019/9/19 - 16:12
 *      这个是传入一个人数总数量，在0到这人数总数量中生产一个随机数集合，达到随机分组的目的
 */
public class RandomNumberListUtil {
    public static List<Integer> getRandomList(Integer totalPeople){
        Random random = new Random();
        //采用list无序集合，目的是存随机生成的随机数
        List<Integer> list = new ArrayList<>();
        while(list.size() < totalPeople ){
            int num = random.nextInt(totalPeople);
            System.out.println(num);
            //防止生成的随机数不重复
            if(!list.contains(num)){
                list.add(num);
            }
        }
        return list;
    }

    public static Map<User,Integer> mapList(List<Integer> list,Integer groupNum,List<User> userList){
        Map<User,Integer> map = new HashMap<>();
        //得到总人数
        int totalPeople = list.size();
        //取平均
        int avg = totalPeople / groupNum;
        //得到剩余的人数
        int last = totalPeople % groupNum;
        //作完整的分组人数的值，拿去循环
        int sum = totalPeople - last;
        //定义组别的下标
        int temp = 0;
        for(int i = 0 ; i < sum; i++){
            if(i % avg == 0){
                temp++;
            }
            map.put(userList.get(list.get(i)),temp);
        }
        //将剩余的人数添加到别的组别去，从最后一组轮流向前的组添加一个人，直到将剩余人数添加进组为止
        while(last > 0){
            map.put(userList.get(list.get(totalPeople-last)),temp);
            last--;
            temp--;
        }
        return map;
    }
    public static void main(String[] args) {
        //模拟五个人分两组
        List<User> userList = new ArrayList<>();
        User user1 = new User();
        user1.setUname("test1");
        User user2 = new User();
        user2.setUname("test2");
        User user3 = new User();
        user3.setUname("test3");
        User user4 = new User();
        user4.setUname("test4");
        User user5 = new User();
        user5.setUname("test5");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        List<Integer> randomList = RandomNumberListUtil.getRandomList(userList.size());
        Map<User, Integer> integerIntegerMap = RandomNumberListUtil.mapList(randomList, 2,userList);
        for(int i = 1; i <= 2 ;i++){
            System.out.println("第"+i+"组人员：");
            for(User user :integerIntegerMap.keySet()){
                if( integerIntegerMap.get(user) == i){
                    System.out.print(user.getUname()+" ");
                }
            }
            System.out.println();
        }
    }
}
